package com.fighYo.trace.controller;


import com.fighYo.trace.entity.Product;
import com.fighYo.trace.entity.Secret;
import com.fighYo.trace.entity.User;
import com.fighYo.trace.service.SecretService;
import com.fighYo.trace.service.UserService;
import com.fighYo.trace.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fighYo
 * @since 2022-04-11
 */
@CrossOrigin
@Slf4j
@Api(tags = {"密保管理"})
@RestController
@RequestMapping("/secret")
public class SecretController {

    @Autowired
    private SecretService secretService;

    @Autowired
    private UserService userService;

    @ApiOperation("获取密保问题")
    @PostMapping("question")
    public R getQuestion(@RequestBody User user) {
        user = userService.getUser(user);
        if (user == null) {
            return R.error().msg("用户不存在");
        }
        Secret secret = secretService.getSecret(user);
        if (secret == null) {
            return R.error().msg("该用户未设置密保");
        } else {
            return R.ok().data("item", secret.getQuestion());
        }
    }

    @ApiOperation(("验证密保"))
    @PostMapping("validate")
    public R validateQuestion(@RequestBody Secret secret) {
        log.info("request body: {}", secret);
        User user = new User();
        user.setUserName(secret.getUserName());
        user.setUserType(secret.getUserType());
        user = userService.getUser(user);
        Secret realSecret = secretService.getSecret(user);
        if (realSecret.getAnswer().equals(secret.getAnswer())) {
            return R.ok().data("item", user.getId());
        } else {
            return R.error().msg("密保验证错误");
        }
    }

    @ApiOperation("添加密保问题")
    @PostMapping("add")
    public R addSecret(@RequestBody Secret secret) {
        boolean result = secretService.save(secret);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("修改密保问题")
    @PostMapping("update")
    public R updateProduct(@RequestBody Secret secret) {
        boolean result = secretService.updateById(secret);
        return result ? R.ok() : R.error();
    }

    @ApiOperation("删除密保问题")
    @PostMapping("delete")
    public R deleteProduct(String secretId) {
        boolean result = secretService.removeById(secretId);
        return result ? R.ok() : R.error();
    }

}

